package com.example.smartvillage.onenet;

import android.util.Log;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class CommonInterceptor implements Interceptor {

    private static final String TAG = "请求拦截器";
    private static final String resourceName = "products/319981";
    private static final String accessKey = "E+eahjEL+uWbb1wy2IypL3HYSj2j18ApwlQtkXYMYW8=";

    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        String token = Auth.assembleToken(resourceName, accessKey);

        Request oldRequest = chain.request();

        // 添加新的url参数
        HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
                .newBuilder()
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host());
                //.addQueryParameter("version", "1");

        // 新的请求
        Request newRequest = oldRequest.newBuilder()
                .method(oldRequest.method(), oldRequest.body())
                .url(authorizedUrlBuilder.build())
                .addHeader("authorization", token)
                .build();
        Log.d(TAG, "实际请求的URL为："+ newRequest.url().toString());
        Log.d(TAG, "实际请求的header中authorization的值为为："+ newRequest.header("authorization"));

        return chain.proceed(newRequest);
    }
}
